<?php


class Ws
{
    const PORT = 8812;
    const HOST = "0.0.0.0";
    public $ws = null;

    public function __construct()
    {

        $this->ws = new swoole_websocket_server("0.0.0.0", self::PORT);
        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 2
        ]);
        $this->ws->on("open", [$this, 'onOpen']);
        $this->ws->on("message", [$this, 'onMessage']);
        $this->ws->on("task", [$this, 'onTask']);
        $this->ws->on("finish", [$this, 'onFinish']);
        $this->ws->on("close", [$this, 'onClose']);
        $this->ws->start();
    }

    public function onOpen(swoole_websocket_server $server, $request)
    {
        echo "client:{$request->fd}--connected\n";
        swoole_timer_tick(3000, function () {
            echo "after 3000ms.\n";
            swoole_timer_after(7000, function () {
                echo "after 7000ms.\n";
            });

        });
    }

    public function onMessage($ws, $frame)
    {

        $data = [
            'task' => 1,
            'fd' => $frame->fd
        ];
        swoole_timer_after(3000, function() use($ws,$frame) {
            $ws->push($frame->fd, "3000ms to client");
        });
        $ws->task($data);
        echo "receive from-{$frame->fd}-data:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $ws->push($frame->fd, "this is server");

    }

    public function onClose(swoole_websocket_server $server, $fd)
    {
        echo "client:{$fd}-closed\n";
    }

    public function onTask($ws, $task_id, $from_id, $data)
    {
        sleep(7);
        echo "New AsyncTask[id=$task_id]" . PHP_EOL;
        //返回任务执行的结果
        $ws->finish("{$data['fd']} -> OK");
    }

    public function onFinish($ws, $task_id, $data)
    {
        echo "AsyncTask[$task_id] Finish: $data" . PHP_EOL;
    }

}

new Ws();
?>
